/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: Hua YY
 * Date: 2025-03-05
 * Time: 21:09
 */
public class Test23 {

      public class ListNode {
      int val;
      ListNode next;
      ListNode() {}
      ListNode(int val) { this.val = val; }
      ListNode(int val, ListNode next) { this.val = val; this.next = next; }
      }
  class Solution {
        public ListNode removeNthFromEnd(ListNode head, int n) {
            // 笨办法 遍历两遍链表，第一遍统计节点数
            ListNode preNode = new ListNode();
            preNode.next = head;
            ListNode curNode = preNode;
            int count = 0;
            //计算长度
            while (curNode != null) {
                curNode = curNode.next;
                count++;
            }


            int targetNum = count - n;
            if (targetNum > count - 1) {
                return null;
            }

            ListNode targetNode = findPreNode(preNode , targetNum);
            if(targetNode.next.next == null){
                targetNode.next = null;
            }else{
                targetNode.next = targetNode.next.next;
            }
            return preNode.next;
        }

        public ListNode findPreNode(ListNode preNode, int targetNum) {
            int count = 1;
            while (count != targetNum) {
                preNode = preNode.next;
                count++;
            }
            return preNode;
        }

    }

}
